package com.wn26.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

@WebFilter(urlPatterns = {"/*"},initParams = @WebInitParam(name = "encoding",value = "utf-8"))
public class CharacterEncondingFilter implements Filter {
	
	private String encoding;

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		//-- 在过滤器初始化时读取过滤器配置对象
		encoding = fConfig.getInitParameter("encoding");
		if (encoding == null || encoding.length() == 0) {
			encoding = "UTF-8";
		}
		
	}
	
	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		//-- 设置请求和响应的编码
		request.setCharacterEncoding(encoding);
		response.setContentType("text/html;charset=utf-8");
		// pass the request along the filter chain
		//-- 请求放行
		chain.doFilter(request, response);
	}


	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		//-- 释放对象.告诉GC这个对象是垃圾!!
		encoding = null;
	}



}
